﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using LSA.Framework;

namespace Visuals.Panes
{
    /// <summary>
    /// Interaction logic for WordsListControl.xaml
    /// </summary>
    public partial class WordsListControl : UserControl
    {
        public ObservableCollection<WordInfo> AllWords { get; set; }

        public Action<WordInfo> Callback { get; set; }
        public Action<WordInfo> AddToGraphCallback { set; get; }

        public WordsListControl(ObservableCollection<WordInfo> words) : this()
        {
            AllWords = words;
        }

        public WordsListControl()
        {
            AllWords = new ObservableCollection<WordInfo>();
            DataContext = this;
            InitializeComponent();

            ICollectionView view = CollectionViewSource.GetDefaultView(wordsPane.Items);
            new TextSearchFilter(view, wordSearchTextbox);
        }

        private void wordsPane_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject obj = (DependencyObject)e.OriginalSource;

            while (obj != null && obj != wordsPane)
            {
                if (obj.GetType() == typeof(ListViewItem))
                {
                    var listItem = (ListViewItem)obj;
                    var content = (WordInfo)listItem.Content;

                    if (Callback == null) return;
                    Callback(content);

                    break;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }
        }

        // TODO: refactor
        private void AddWordToGraph(object sender, RoutedEventArgs e)
        {
            if (AddToGraphCallback == null) return;
            if (e.Handled) return;

            var word = (WordInfo) ((ListViewItem) ((ContextMenu)((MenuItem) e.OriginalSource).Parent).PlacementTarget).DataContext;
            AddToGraphCallback(word);
        }

        private void OpenSearchWindow(object sender, RoutedEventArgs e)
        {
            var word = (WordInfo)((ListViewItem)((ContextMenu)((MenuItem)e.OriginalSource).Parent).PlacementTarget).DataContext;
            MainWindow.Object.OpenNewSearchPreview(word.Word); // TODO: callback
        }

        public IList GetSelectedWords()
        {
            return wordsPane.SelectedItems;
        }
    }
}
